import 'package:dio/dio.dart';
import 'package:mall/core/models/product_detail.dart';
import 'package:mall/core/services/api.dart';
import 'package:mall/core/providers/view_model.dart';

/// 商品详情
class ProductDetailModel extends ViewModel {
  final Api api;
  final int aId;
  final int pid;
  final int mid;
  final int referStoreId;

  String _errorMessage;
  ProductDetail _productDetail;

  ProductDetailModel(
    this.api,
    this.aId,
    this.pid,
    this.mid,
    this.referStoreId,
  ) : super() {
    _initData();
  }

  String get errorMessage => _errorMessage;

  ProductDetail get productDetail => _productDetail;

  Future<ViewState> _initData() async {
    viewState = ViewState.busy;
    try {
      _productDetail = await api.productDetail(aId, pid, mid, referStoreId, cancelToken);
      if (_productDetail.skus == null || _productDetail.skus.isEmpty) {
        _errorMessage = "商品数据异常，请稍后再试。";
        viewState = ViewState.error;
      } else {
        viewState = ViewState.success;
      }
    } on DioError catch (e) {
      _errorMessage = e.message;
      viewState = ViewState.error;
    } catch (e) {
      _errorMessage = e.toString();
      viewState = ViewState.error;
    }
    return viewState;
  }
}
